import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import 'font-awesome/css/font-awesome.min.css';
import axios from 'axios';
import qs from 'qs';
import {
  getCurDate,
  setSessionStorage,
  getSessionStorage,
  removeSessionStorage,
  setLocalStorage,
  getLocalStorage,
  removeLocalStorage
} from './common.js';

// 设置 axios 的基础 url 部分
axios.defaults.baseURL = 'http://127.0.0.1:8080/elm/';    // x.x.x.x 换成部署了网关服务器的主机的公网 IP

// 创建 Vue 3 应用实例
const app = createApp(App);

// 将 axios 和其他工具挂载到全局属性上
app.config.globalProperties.$axios = axios;
app.config.globalProperties.$qs = qs;
app.config.globalProperties.$getCurDate = getCurDate;
app.config.globalProperties.$setSessionStorage = setSessionStorage;
app.config.globalProperties.$getSessionStorage = getSessionStorage;
app.config.globalProperties.$removeSessionStorage = removeSessionStorage;
app.config.globalProperties.$setLocalStorage = setLocalStorage;
app.config.globalProperties.$getLocalStorage = getLocalStorage;
app.config.globalProperties.$removeLocalStorage = removeLocalStorage;

// 路由守卫
router.beforeEach((to, from, next) => {
  let user = sessionStorage.getItem('user');
  let business = sessionStorage.getItem('business');
  
  // 公开路由白名单（不需要登录的页面）
  const publicRoutes = [
    '/', 
    '/index', 
    '/businessList', 
    '/businessInfo', 
    '/login', 
    '/register', 
    '/businessRegister'
  ];
  
  // 商家专属路由（需要商家登录）
  const businessRoutes = [
    '/businessManager',
    '/foodManager'
  ];
  
  // 如果是公开路由，直接通过
  if (publicRoutes.includes(to.path)) {
    next();
    return;
  }
  
  // 如果是商家路由，检查商家登录状态
  if (businessRoutes.includes(to.path)) {
    if (business === null) {
      router.push('/login');
      return;
    }
    next();
    return;
  }
  
  // 其他路由检查用户登录状态
  if (user === null) {
    router.push('/login');
    return;
  }
  
  next();
});

// 使用路由
app.use(router);

// 挂载应用
app.mount('#app');